<?php


namespace App\Twig;

use App\Entity\Menu;
use App\Entity\Page;
use App\Utils\Helper\GetterHelper;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class MenuExtension extends AbstractExtension {
    public function getFunctions () {
        return [
            new TwigFunction('menu', [$this, 'getCurrentMenu']),
        ];
    }

    public function getCurrentMenu ($document_uri) {
        $result = '';

        $items = explode('//', $document_uri);
        if (isset($items[1])) {
            $parts = explode('/', $items[1]);
            if (count($parts) == 1) {
                $result = $items[1];
            } else {
                if ($parts[0] == 'article') {
                    $id = $parts[1] ?? 0;
                    $page = GetterHelper::getEntityManager()->getRepository(Page::class)->find($id);
                    if (is_object($page)) {
                        $menu = GetterHelper::getEntityManager()->getRepository(Menu::class)->findOneBy(['page_category_id' => $page->getPageCategoryId()]);
                        if (is_object($menu)) {
                            $result = $menu->getAlias();
                        }
                    }
                } else {
                    array_shift($parts);
                    $result = implode('/', $parts);
                }
            }
        }

        return $result;
    }
}